import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)


//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//重写原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  // 调用原来的push函数，并捕获异常  call（显示改变this指向  js中this指向）
  return originalPush.call(this, location).catch(err => err)
}

// 模块化： ES6  commonjs

// 配置路由匹配规则
const routes = [{
  path: "/login",
  component: () => import("../views/login/index.vue")
}, {
  path: "/",
  component: () => import("../views/index/index.vue"),
  children: [{ //二级路由 ‘/’ 可以不写
      path: "menu",
      meta: {
        title: "菜单管理"
      },
      component: () => import("../views/menu/index.vue")
    },
    {
      path: "role",
      meta: {
        title: "角色管理"
      },
      component: () => import("../views/role/index.vue")
    },
    {
      path: "user",
      meta: {
        title: "管理员管理"
      },
      component: () => import("../views/user/index.vue")
    }
  ]
}, {
  path: "/menu",
  component: () => import("../views/menu/index.vue")
}]

// 获取路由实例
const router = new VueRouter({
  // 路由模式
  mode: "hash",
  // 路由规则
  routes
})

// 导出
export default router


// 检测是否登录
router.beforeEach((to, from, next) => {
  // to:去哪
  // from:从哪里来
  // next(): 继续执行函数next
  // console.log(to)
  // console.log(from)

  // 1.获取本地缓存中的用户信息
  let userInfo = localStorage.getItem('userInfo') || ""
  // 2.检测是否有数据
  if (userInfo == "" && to.path != "/login") {
    alert('请先登录')
    next('/login')
  } else {
    next()
  }

  // 常见错误：Maximum call stack size exceeded  内存溢出，路由死循环导致

  // this.$router VS this.$route

})